<?php
namespace control;
/*
*劳动合同类
*/

class workContractClass extends adIndexClass
{
    private const table = 'staff_contract';
    private const page = 'workContract';
    private const title = '劳动合同';
    public const contractLimitType=['固定期限','无固定期限'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "姓名" => text(array("name" => "name")),
                    "部门"     => selectMultiple(array("name" => "departmentId", "table" => "department", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                    '职位' => selectMultiple(array("name" => "jobId", "table" => "job", 'where' => "1=1 order by list asc", 'sqlField' => 'name', 'sqlId' => 'id', 'class' => 'width200')),
                ],
                [
                    "身份证号" => text(array("name" => "idCard")),
                    "手机号" => text(array("name" => "tel")),
                    "入职日期" => text(array("name" => "startTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "合同状态" => select(["name" => "workFlow", 'option' => [
                        "draft" => "待新签",
                        "signing" => "待续签",
                        "effecting" => "生效中",
                        "lift" => "已解除",
                        "ending" => "已终止",
                    ]]),
                ]

            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*行政人事-出差记录-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }
    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => '合同编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => '姓名',
                        'width' => 150,
                    ],
                    'department'  => [
                        'name'  => '部门',
                        'width' => 200,
                    ],
                    'job'         => [
                        'name'  => '职位',
                        'width' => 150,
                    ],
                    'idCard'          => [
                        'name'  => '身份证号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'tel'          => [
                        'name'  => '手机号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'entryDate'          => [
                        'name'  => '入职日期',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'days'          => [
                        'name'  => '入职天数',
                        'width' => 130,
                    ],
                    'state'          => [
                        'name'  => '在职状态',
                        'width' => 130,
                    ],
                    'workFlow'          => [
                        'name'  => '合同状态',
                        'width' => 130,
                    ]
                ];
        }
        return $tr;
    }

    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        $warnDay = para('workContractWarnDay');
        //全等查询数组
        $equal = array(
            "a.jobId" => $this->post('jobId'),
        );
        //like查询数组
        $like = array(
            "b.name" => $this->post('name'),
            "b.idCard" => $this->post('idCard'),
            "b.tel" => $this->post('tel'),
        );
        //初始化
        $and = "";
        //合同状态
        if($this->post('workFlow')){
            switch ($this->post('workFlow')) {
                case "draft":
                    $and .= " and a.workFlow = '待新签' ";
                    break;
                case "signing":
                    //找生效中且合同结束日期小于提醒天数的 和 合同正常终止但未离职的
                    $and .= " and isClose = 0 and contractLimitType = '固定期限' and ((a.workFlow = '生效中' and DATEDIFF(signEndDate,DATE_FORMAT(now(),'%Y-%m-%d')) <= '$warnDay') or (a.workFlow = '已终止' and isQuit = 0))";
                    break;
                case "effecting":
                    $and .= " and isClose = 0 and a.workFlow = '生效中' ";
                    break;
                case "lift":
                    $and .= " and a.workFlow = '已解除' ";
                    break;
                case "ending":
                    $and .= " and a.workFlow = '已终止' and contractLimitType = '固定期限' ";
                    break;
            }
        }
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'), field: 'entryDate');
        }
        if ($this->post('departmentId')) {
            $and .= " and a.jobId in (select id from job where departmentId = '" . $this->post('departmentId') . "')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.entryDate desc,a.orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join talent_pool as b on a.talentId = b.id",
            'field' => "a.*,b.name,b.idCard,b.tel",
            "where" => $where,
            "order" => $orderBy['orderBy']));
        //获取表头
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "edit" => $array['workFlow']=='待新签'?array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"):'',
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            $job = query('job', "id = '$array[jobId]'");
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "department":
                        $row[] = departmentClass::getTypeName($job['departmentId']);
                        break;
                    case "job":
                        $row[] = $job['name'];
                        break;
                    case "days":
                        $row[] = $this->countDay($array['entryDate'], $this->date);
                        break;
                    case "state":
                        $staff = query('staff', "stid = '$array[staffId]'");
                        $row[] = $staff['state'];
                        break;
                    case "workFlow":
                        if($array['isClose'] == 0 && $array['workFlow'] == '生效中'){
                            $row[] = '生效中';
                        }elseif($array['isClose'] == 0 && $array['contractLimitType'] == '固定期限' && (($array['workFlow'] == '生效中' && self::diffDays($array['signEndDate'], $this->time) <= $warnDay) || ($array['workFlow'] == '已终止' && $array['isQuit'] == 0))){
                            $row[] = '待续签';
                        }else{
                            $row[] = $array['workFlow'];
                        }
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        if ($this->get('sourceId')) {
            //续签合同
            $info = query(self::table, " id = '" . $this->get('sourceId') . "' ");
        }
        $talent = query('talent_pool', "id = '$info[talentId]'");
        $staff = query('staff', "stid = '$info[staffId]'");
        //按钮
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "cla" => $this->get('cla'),
            "fun" => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            "post" => ["id" => $id],
            'style' => 'li-btn-blue-bg',
        ];
        $job = query('job', "id = '$info[jobId]'");
        $departmentName = departmentClass::getTypeName($job['departmentId']);
        //表单
        $data['button'] = $this->tableShowButton($button);
        $data['html'] = $this->pageEdit([
            "table" => [
                '员工基本信息' => [
                    [
                        "姓名：" => $talent['name'],
                        "身份证号：" => $talent['idCard'],
                        '手机号：' => $talent['tel'],
                        "部门：" => departmentClass::getTypeName($job['departmentId']),

                    ],
                    [
                        "职位：" => $job['name'],
                        '入职日期：' => $info['entryDate'],
                        '试用期至：' => $info['endDate'],
                        '在职状态：' => $staff['state'],
                    ],
                ],
                '合同信息' => [
                    [
                        must . "入职日期：" => text(["name" => "entryDate", 'laydate' => [], "value" => $info['entryDate']]),
                        must . "试用期至：" => text(["name" => "endDate", 'laydate' => [], "value" => $info['endDate']]),
                        must . "合同类型：" => radio(["name" => "contractType", 'value' => explode('，', para('contractTypeOption')), "checked" => $info['contractType'] ?: '劳动合同']),
                        must . "合同期限：" => select(array('name' => 'contractLimitType', 'title' => '请选择', 'class' => 'width100', 'value' => $info['contractLimitType']?:'固定期限', 'option' => ['固定期限','无固定期限'])).text(["name" => "contractYear", 'blur' => 'getEndDate', 'other' => " min='0' ", 'type' => "number", 'unit' => "月", 'class' => 'width100', "value" => $info['contractYear']]),
                    ],
                    [
                        must . "合同签订日期：" => text(["name" => "signDate", 'laydate' => [], "value" => $info['signDate'] ?: $this->date]),
                        must . "合同起止日期：" => text(["name" => "signStartDate", 'laydate' => [], 'class' => 'width100', "value" => $info['signStartDate'] ?: $info['entryDate']]) . "至\n" . text(["name" => "signEndDate", 'laydate' => [], 'class' => 'width100', "value" => $info['signEndDate']]),
                        must . "拟任职位：" => selectMultiple([
                            "name" => "jobId", "title" => "拟任职位",
                            'value' => $info['jobId'],
                            'sqlField' => 'name',
                            'sqlId' => 'id',
                            'table' => "job",
                            'where' => "1=1 order by list",
                            'change' => 'getJobInfo'
                        ]),
                        '职位类型：' => "<span id='jobType'>{$job['type']}</span>",
                    ],
                    [
                        '所属部门：' => "<span id='department'>$departmentName</span>",
                        "直属上级：" => selectMultiple([
                            "name" => "managerId", "title" => "直属上级",
                            'value' => $info['managerId'],
                            'sqlField' => 'name',
                            'sqlId' => 'stid',
                            'table' => "staff",
                        ]),
                        must . "劳动报酬：" => text(["name" => "workSalary", "value" => $info['workSalary']]),
                        must . "社会保险：" => text(["name" => "insure", "value" => $info['insure']]),
                    ],
                    [
                        "备注：" => textarea(["name" => "workText", "value" => $info['text']]),
                    ],
                ],
                '合同附件' => [
                    [
                        fileUploadClass::addFileComponent($info['id'], '劳动合同', self::page, self::page . 'EditForm'),
                    ]
                ]
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $id)) . hidden(array('name' => 'sourceId', 'value' => $this->get('sourceId'))),
        ]);
        $data['html'] .= $this->editJs();
        //返回
        return $this->tab($data);
    }

    public function editJs()
    {
        return <<<eof
<script>
function getEndDate(e){
    let startDate = $("[name = 'entryDate']").val();
    let year = Number(e.value);
    let contractLimitType = $("[name='contractLimitType']:checked").val();
    if (contractLimitType ==='固定期限'){
        var now = new Date(startDate);
        var newDate = DateAdd(year, now);
         console.log(newDate)
        let str = newDate.Format("yyyy-MM-dd");
        $("[name='signEndDate']").val(str)
    }else{
         $("[name='signEndDate']").val('')
    }
}
function DateAdd(number, date) {
     date.setFullYear(date.getFullYear(),date.getMonth()+ number);
        return date;
    }
 function getJobInfo(e){
   let id = e.value;
   $.post(root+'control/adIndex.html?cla=talentPool&fun=getJobInfo',{id:id},function(res) {
        $("#jobType").html(res.data.jobType);
         $("#department").html(res.data.department);
   },'json')
 }

</script>
eof;

    }

    /**
     * 计算日期间的天数
     * @param $startDate
     * @param $endDate
     * @return string
     * @throws Exception
     */
    public function countDay($startDate, $endDate): string
    {
        $dStart = new \DateTime($startDate);
        $dEnd = new \DateTime($endDate);
        $dDiff = $dStart->diff($dEnd);
        return $dDiff->format('%r%a');
    }



    public function judgeIsDiff($info, $field, $annotation)
    {
        $text = '';
        foreach ($field as $k => $val) {
            if ($val != $info[$k]) {
                $text .= $annotation[$k] . "从" . $info[$k] . '更新至' . $val . "<br>";
            }
        }
        if ($text) {
            $this->insertRecord(array(
                'text' => $text,
                'contractId' => $info['id'],
            ));
        }
    }

    public function insertRecord($field): string
    {
        $field = array_merge(
            $field,
            [
                'id' => suiji(),
                'name' => $this->control['name']
            ]
        );
        return static::insert(array(
            'table' => 'staff_contract_change',
            'field' => $field
        ));
    }

    /*编辑*/
    public function editEdit()
    {
        $id = $this->post('id');
        $sourceId = $this->post('sourceId');
        $field = [
            'jobId' => $this->post('jobId'),
            'managerId' => $this->post('managerId'),
            'entryDate' => $this->post('entryDate'),
            'endDate' => $this->post('endDate'),
            'text' => $this->post('workText'),
            'contractType' => $this->post('contractType'),
            'contractYear' => $this->post('contractYear'),
            'contractLimitType' => $this->post('contractLimitType'),
            'workSalary' => $this->post('workSalary'),
            'insure' => $this->post('insure'),
            'signDate' => $this->post('signDate'),
            'signStartDate' => $this->post('signStartDate'),
            'signEndDate' => $this->post('signEndDate'),
        ];
        $annotation = [
            'jobId' => '拟任职位',
            'managerId' => '直属上级',
            'entryDate' => '入职日期',
            'endDate' => '试用期至',
            'text'=>'备注',
            'contractType' => '合同类型',
            'contractYear' => '合同期限',
            'contractLimitType' => '合同期限类型',
            'signDate' => '合同签订日期',
            'signStartDate' => '合同起始日期',
            'signEndDate' => '合同结束日期',
            'workSalary' => '劳动报酬',
            'insure' => '社会保险',
        ];
        $rules = [
            'jobId' => 'required',
            'entryDate' => 'required',
            'endDate' => 'required',
            'contractType' => 'required',
            'contractLimitType' => 'required',
            'signDate' => 'required|date',
            'signStartDate' => 'required|date',
            'workSalary' => 'required',
            'insure' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $entryResult = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($entryResult === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "您还没有编辑权限";
        } elseif (empty($info['id']) && empty($sourceId)) {
            $json['warn'] = '未找到此合同';
        } elseif ($field['contractLimitType'] == '固定期限' && empty($field['signEndDate'])) {
            $json['warn'] = '请选择合同截止日期';
        } elseif ($field['contractLimitType'] == '固定期限' && strtotime($field['signEndDate']) <= strtotime($field['signStartDate'])) {
            $json['warn'] = '合同截止日期不能小于起始日期';
        } else {
            if ($field['contractLimitType'] == '无固定期限') {
                $field['contractYear'] = 0;
                $field['signEndDate'] = '';
            }
            if (empty($info['id']) && $sourceId) {
                $source = query(self::table, "id = '$sourceId'");

                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $field = array_merge($field, [
                    'id' => suiji(),
                    'talentId' => $source['talentId'],
                    'staffId' => $source['staffId'],
                    'workFlow' => '生效中',
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                ]);
                $userNo = codeTemplateClass::generateCode('workContract',[
                    'prefix' => 'LDHT' . date('Ymd'),
                    'table' => 'staff_contract',
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field['orderNo'] = $userNo;
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $userNo = $info['orderNo'];
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                if ($sourceId) {
                    $oldField['isClose'] = 1;
                    //续签
                    $oldContract = query(self::table, "id = '$sourceId'");
                    if ($oldContract['signEndDate'] >= $field['signStartDate']) {
                        $oldField['workFlow'] = '已终止';
                    }
                    update(array('table' => self::table, 'field' => $oldField, 'where' => "id = '$oldContract[id]'"));
                    $this->insertRecord(array(
                        'contractId'=> $sourceId,
                        'text'=>'新合同【'.$userNo.'】生效，此合同终止'
                    ));
                }else{
                    $this->judgeIsDiff($info, $field, $annotation);
                }
                //附件
                $fileIdArr = $this->post('fileId');
                if (is_array($fileIdArr)) {
                    update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $sourceId ? '续签成功' : $json['warn'];
                $json['warn'] = 2;
            }

        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }


    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];
                //按钮
                if ($this->power(self::page, "edit") && $info['workFlow'] == '待新签') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                $warnDay = para('workContractWarnDay');
                if (!$info['isClose'] && ($info['workFlow'] == '待续签' || ($info['workFlow'] == '生效中' && $this->countDay($this->date,$info['signEndDate']) < $warnDay) || ($info['workFlow']=='已终止' && !$info['isQuit'])) && $this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "续签",
                        "type" => "顶部页卡",
                        "title" => "劳动合同详情",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&sourceId=" . $info['id'],
                    ];
                }

                if ($this->power(self::page, "edit") && in_array($info['workFlow'], ['待新签', '待续签'])) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
                $tr[] = ['变更日期', '变更人', '变更内容'];
                $all = find(array('table' => 'staff_contract_change', 'where' => "contractId = '$info[id]' order by time desc"));
                foreach ($all['array'] as $array) {
                    $tr[] = [$array['time'], $array['name'], $array['text']];
                }

                $staff = query('staff', "stid = '$info[staffId]'");
                $talent = query('talent_pool', "id = '$info[talentId]'");
                $job = query('job', "id = '$info[jobId]'");
                $staffEntry = query('staff_entry_record', "talentId = '$talent[id]' order by time desc");
                $staffFormal = query('staff_formal', "staffId = '$info[staffId]' order by time desc");
                //生成表单
                $data['button'] = $this->tableShowButton($button);
                $data['html'] = $this->tableShow(array(
                    '员工基本信息' => array(
                        array(
                            "姓名" => $talent['name'],
                            "身份证号" => $talent['idCard'],
                            "手机号" => $talent['tel'],
                            "部门" => departmentClass::getTypeName($job['departmentId']),
                        ),
                        array(
                            "职位" => $job['name'],
                            "入职日期" => $staffEntry['entryDate'],
                            "转正日期" => $staffFormal['confirmDate'],
                            "在职状态" => $staff['state'],
                        ),
                    ),
                    '合同信息' => array(
                        array(
                            "入职日期" => $info['entryDate'],
                            "试用期至" => $info['endDate'],
                            "合同类型" => $info['contractType'],
                            "合同期限" => $info['contractLimitType'] == '固定期限' ? $info['contractLimitType'] . $info['contractYear'] . '个月' : $info['contractLimitType'],
                        ),
                        array(
                            "劳动报酬" => $info['workSalary'],
                            "社会保险" => $info['insure'],
                            "合同签订日期" => $info['signDate'],
                            "合同起止日期" => $info['signStartDate'] . '至' . ($info['contractLimitType'] == '固定期限'?$info['signEndDate']:$info['contractLimitType']),
                        ),
                        array(
                            "合同解除/终止日期" => $info['stopDate'],
                        ),
                        array(
                            "备注" => pre($info['text']),
                        ),
                    ),
                    '附件' => array(
                        array(
                            fileUploadClass::showFile($info['id'])
                        ),
                    ),
                ));
                $data['html'] .= $this->detailList([
                    'title' => '变更记录',
                    'html' => $this->listTable(array('tr' => $tr, 'showSort' => true)),
                ]);
                $data['html']   .= $this->tableShow(array(
                    '系统信息' => array(
                        array(
                            '合同编号' => $info['orderNo'],
                            '合同状态' => $info['workFlow'],
                            '创建人' => self::findStaff($info['stid']),
                            '创建时间' => $info['time'],
                        ),
                        array(
                            '更新时间' => $info['updateTime'],
                        )
                    )
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }


    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'workFlow' => '生效中',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此劳动合同';
        } elseif ($info['workFlow'] != '待新签') {
            $json['warn'] = '此合同不是待新签状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->insertRecord(array(
                    'text' => $this->control['name'] . "提交了参保信息",
                    'contractId' => $info['id']
                ));
                //生成劳动合同到期提醒
                /*$setting = self::getSettingValue('laborContract');
                $startDay = date("Y-m-d",strtotime("-".$setting['threshold']." days", strtotime($info['signEndDate'])));
                foreach ($setting['member'] as $item){
                    backlogIn([
                        "stid"      => $item,
                        "type"      => '提醒消息',
                        "typeId"    => $info['id'],
                        "text"      => "劳动合同" . "【" . $info['orderNo'] . "】将在".$info['signEndDate']."到期",
                        "startDay"  => $startDay,
                        "targetCla" => 'workContract',
                        "targetFun" => 'detail',
                    ]);
                }*/
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功，合同生效中';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


}
